package com.wsx.sky.redis;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.redis.RedisService
 * @Description: TODO
 * @date 2018/12/07
 */
@Service
public class RedisService {

    private static Gson gson = new Gson();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public void init() {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
    }


    public String getString(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void setString(String key, String value, int seconds) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }


    public void setString(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void delString(String key) {
        redisTemplate.delete(key);
    }

    public void setObject(String key, Object obj) {
        redisTemplate.opsForValue().set(key, gson.toJson(obj));
    }
    public <T> T getObject(String key, Class<T> clazz) {
        String value = getString(key);
        return gson.fromJson(value, clazz);
    }

    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

}
